import { useState, useEffect } from 'react';
import { Collapse, Input, Form, Button, Modal, CheckList, Popup } from 'antd-mobile';
import { AddOutline, MinusOutline, DeleteOutline } from 'antd-mobile-icons';
import { useHistory } from 'react-router-dom';

export default function() {
  const history = useHistory();
  const [showAddNewEnvInfo, setShowAddNewEnvInfo] = useState(false);
  const [chosenEnvInfo, setChosenEnvInfo] = useState(['公有云-生产']);

  const [envInfoList, setEnvInfoList] = useState([{
    "name": "公有云-生产",
    "socketUrl": "wss://ccmimplus-ws.cloud.alipay.com:443/ws",
    "endpoint": "https://ccmimplus.cloud.alipay.com"
  },{
    "name": "公有云-预发",
    "socketUrl": "wss://ccmimplusvpcpre-ws.cloud.alipay.com:443/ws",
    "endpoint": "https://ccmimplusvpcpre.cloud.alipay.com"
  },{
    "name": "公有云-sit",
    "socketUrl": "ws://116.62.45.200:80/ws",
    "endpoint": "https://47.110.154.236"
  }]);

  useEffect(() =>{
    const localEnvInfo = localStorage.getItem('implusLocalEnvInfo');
    const chosenEnvData = localStorage.getItem('chosenEnvInfo');

    if(localEnvInfo) {
      setEnvInfoList(JSON.parse(localEnvInfo))
    }

    if(chosenEnvData) {
      setChosenEnvInfo(JSON.parse(chosenEnvData));
    }
  }, [])

  const storeNewInfo = (data, dataList, setAction, key ) => {
    data.isNew = true;
    const newdata = [...dataList];
    newdata.push(data);
    setAction(newdata);
    localStorage.setItem(key, JSON.stringify(newdata));
  }

  const storChosenInfo = (data, key, setAction) => {
    localStorage.setItem(key, JSON.stringify(data));
    setAction(data);
  }

  const deleteInfo = (e, dataList, setAction, storekey, idx) => {
    e.stopPropagation();
    Modal.confirm({
      content: '是否删除该数据',
      closeOnAction: true,
      cancelText: '取消',
      confirmText: '确定',
      onConfirm: () => {
        const newdata = [...dataList]
        newdata.splice(idx, 1);
        setAction(newdata);
        localStorage.setItem(storekey, JSON.stringify(newdata));
      },
      onCancel: () => {
        Modal.clear();
      }
    })
  }

  const confirmInfo = () => {
    // const tntData = tntInfoList.find( t => t.tntInstId === chosenTntInfo[0]);
    const envData = envInfoList.find( e => e.name === chosenEnvInfo[0]);
    Object.entries({...envData}).forEach( (c) => {
      const [key, val] = c;
      if(!(key == 'isNew' || key == 'name') && val) {
        (document as any).cookie = `im_${key}=${val}`;
      }
    });
    history.goBack();
  }

  return (<>
    <Collapse defaultActiveKey={['tnt', 'env']} arrow={active => (active ? <MinusOutline /> : <AddOutline />)}>
      <Collapse.Panel key='env' title='修改网络信息'>
        <CheckList value={chosenEnvInfo} onChange={e => storChosenInfo(e, 'chosenEnvInfo', setChosenEnvInfo)}>
          {
            envInfoList.map( (env, envIdx) => {
              const { name, isNew } = env;
              return <CheckList.Item key={name} value={name}>
                {name}
                {isNew? <DeleteOutline onClick={e => deleteInfo(e, envInfoList, setEnvInfoList, 'implusLocalEnvInfo', envIdx)} style={{ float: 'right', color: 'red', marginTop: '4px'}} /> : null}
                </CheckList.Item>
            })
          }
          <Button style={{width: '100%'}} color='primary' onClick={() => setShowAddNewEnvInfo(true)}>新增</Button>
        </CheckList>
      </Collapse.Panel>
    </Collapse>
    <Popup
      visible={showAddNewEnvInfo}
      onMaskClick={() => setShowAddNewEnvInfo(false) }
      bodyStyle={{ height: '60vh' }}
    >
      <Form
        onFinish={(e) => {
          setShowAddNewEnvInfo(false)
          storeNewInfo(e, envInfoList, setEnvInfoList, 'implusLocalEnvInfo');
        }}
        footer={
          <Button block type='submit' color='primary' size='large'>
            确定
          </Button>
        }
      >
        <Form.Item
          name='name'
          label='name'
          rules={[{ required: true, message: '名称不能为空' }]}
        >
          <Input placeholder='请输入网络名称名称' />
        </Form.Item>
        <Form.Item
          name='socketUrl'
          label='socketUrl'
          rules={[{ required: true, message: '不能为空' }]}
        >
          <Input placeholder='如: wss://192.168.0.1:8000/ws' />
        </Form.Item>
        <Form.Item
          name='endpoint'
          label='endpoint'
          rules={[{ required: true, message: '不能为空' }]}
        >
          <Input placeholder='如: https://ccmimplus.cloud.alipay.com' />
        </Form.Item>
        <Form.Item
          name='mediaHost'
          label='mediaHost'
        >
          <Input placeholder='如: http://common.oss.vpaas.mesh' />
        </Form.Item>
      </Form>
    </Popup>
    <Button style={{position: 'absolute', bottom:'0', left:'0'}} block color='primary' size='large' onClick={() => confirmInfo()}>
      确定变更
    </Button>
  </>)
}